<template>
  <section class="xm-content xm-menu">
    <el-form
      ref="form"
      v-loading="box_loading"
      :model="form"
      :rules="rules"
      size="mini"
      label-width="100px"
      inline-message
    >
      <el-form-item label="类型值">
        <el-radio-group v-model="form.level" prop="level">
          <el-radio :label="0">目录级</el-radio>
          <el-radio :label="1">菜单级</el-radio>
          <el-radio :label="2">按钮级</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item v-if="form.level === 0" label="目录名称" prop="name">
        <el-input
          v-model="form.name"
          placeholder="目录级无上级parentId"
          clearable
        />
      </el-form-item>
      <el-form-item v-if="form.level === 1" label="菜单名称" prop="name">
        <el-input
          v-model="form.name"
          clearable
          placeholder="绝大部分情况菜单都配合URL出现，只有少部分情况比如三级菜单，菜单当作目录使用，才不要求填写URL"
        />
      </el-form-item>
      <el-form-item v-if="form.level === 2" label="按钮名称" prop="name">
        <el-input
          v-model="form.name"
          clearable
          placeholder="绝大部分情况菜单都配合URL出现，只有少部分情况比如三级菜单，菜单当作目录使用，才不要求填写URL"
        />
      </el-form-item>
      <el-popover
        v-show="form.level !== 0"
        placement="bottom-start"
        width="240"
        trigger="click"
        :visible-arrow="true"
        :offset="100"
      >
        <el-form-item slot="reference" label="上级菜单">
          <el-input
            v-model="form.pName"
            placeholder="请选择上级菜单（这fitler过滤掉按钮菜单）"
          />
        </el-form-item>
        <div style="height: 400px; overflow-x: hidden;">
          <el-tree
            ref="mytree"
            v-model="form.parentId"
            :data="superMenu"
            node-key="id"
            :props="{ label: 'name' }"
            :filter-node-method="filterNode"
            default-expand-all
            show-checkbox
            :check-on-click-node="true"
            :check-strictly="true"
            :expand-on-click-node="false"
            @check-change="checkChange"
          >
            <span slot-scope="{ node, data }" class="custom-tree-node">
              <span style="width: 200px;">
                {{ node.label }}
                <span v-if="data.level === 0" style="color: green;"
                  >[目录]</span
                >
                <span v-if="data.level === 1" style="color: green;"
                  >[菜单]</span
                >
              </span>
              <span
                ><span v-if="data.level === 2" style="color: #666;"
                  >按钮</span
                ></span
              >
            </span>
          </el-tree>
        </div>
      </el-popover>
      <el-form-item
        v-if="form.level !== 2"
        label="菜单路由"
        :prop="form.level === 1 ? 'path' : ''"
      >
        <el-input v-model="form.path" placeholder="请输入菜单路由" clearable />
      </el-form-item>
      <el-popover
        v-show="form.level !== 2"
        placement="bottom-start"
        width="276"
        trigger="click"
        :visible-arrow="true"
        :offset="100"
      >
        <el-form-item slot="reference" label="菜单图标">
          <el-input
            v-model="form.icon"
            placeholder="请选择菜单图标"
            clearable
          />
        </el-form-item>
        <div style="height: 300px; overflow-x: hidden;">
          <i
            v-for="(item, index) in elementIcon"
            :key="index"
            :style="{
              'font-size': '28px',
              margin: '3px 0 0 3px',
              cursor: 'pointer',
              color: item.icon == form.icon ? '#56A9FF' : '#606266',
              'font-weight': item.icon == form.icon ? '700' : '400',
            }"
            :class="item.icon"
            @click="handleIconItem(item.icon)"
          >
          </i>
        </div>
      </el-popover>
      <el-form-item label="排序" prop="sortNumber">
        <el-input-number
          v-model="form.sortNumber"
          :step="1"
          :min="1"
          step-strictly
        />
      </el-form-item>
      <el-form-item v-if="form.level === 2" label="授权标识" prop="permission">
        <el-select v-model="form.permission" placeholder="请选择授权标识">
          <el-option
            v-for="item in permissionList"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          >
            <span style="float: left">{{ item.label }}</span>
            <span style="float: right; color: #8492a6;">{{ item.value }}</span>
          </el-option>
        </el-select>
      </el-form-item>
    </el-form>
    <div class="xm-footer">
      <el-button
        type="primary"
        size="mini"
        :loading="btn_loading"
        @click="saves('form')"
        >确 定</el-button
      >
      <el-button type="info" size="mini" @click="close">关 闭</el-button>
    </div>
  </section>
</template>

<script>
import { elementIcon } from '@/mocks/elementIcon.js'
import { getMenuList, addMenu, editMenu } from '@/api/user'
export default {
  props: {
    layerid: {
      default: 0,
    },
    row: {
      default: {},
    },
  },
  data() {
    return {
      box_loading: false,
      btn_loading: false,
      form: {
        id: '',
        name: '', //权限名称
        level: 0, //权限等级
        path: '',
        parentId: '', //上级ID
        pName: '', //上级name
        icon: '', //icon
        sortNumber: 1, //sortNumber  排序
        permission: '', //权限标识
      },
      rules: {
        level: [{ required: true, message: '必选', trigger: 'change' }],
        name: [{ required: true, message: '必填', trigger: 'blur' }],
        icon: [{ required: true, message: '必填', trigger: 'blur' }],
        parentId: [{ required: true, message: '必填', trigger: 'blur' }],
        path: [{ required: true, message: '必填', trigger: 'blur' }],
        sortNumber: [{ required: true, message: '必填', trigger: 'blur' }],
        permission: [{ required: true, message: '必填', trigger: 'blur' }],
      },
      superMenu: [],
      elementIcon: elementIcon,
      permissionList: [
        { label: '添加权限', value: 'add' },
        { label: '编辑权限', value: 'edit' },
        { label: '删除权限', value: 'delete' },
        // { label: '审核权限', value: 'examine' },
        // { label: '启用禁用', value: 'change' },
        // { label: '模版下载', value: 'export' },
        // { label: '批量导入', value: 'import' },
      ],
    }
  },
  watch: {
    'form.level': function(val) {
      if (val !== 0) {
        this.$nextTick(() => {
          this.$refs.mytree.filter(3)
        })
      }
    },
  },
  mounted() {
    if (this.row.id) this.form = JSON.parse(JSON.stringify(this.row))
    this.getSuperMenu()
  },
  methods: {
    // 初始化菜单总树
    async getSuperMenu() {
      this.box_loading = true
      const { data } = await getMenuList({})
      this.box_loading = false
      this.superMenu = this.getMenu(
        JSON.parse(JSON.stringify(data.children)),
        []
      )
      if (this.row.id && this.form.level !== 0) {
        this.$refs.mytree.setCheckedKeys([this.row.parentId])
      }
    },
    getMenu(origin, cur) {
      if (String(origin) === '' || !origin) {
        return cur
      } else {
        origin.forEach((item) => {
          if (item.level == 0 || item.level == 1) {
            cur.push(item)
            if (String(item.children) !== '' || !origin)
              item.children = this.getMenu(item.children, [])
          }
        })
      }
      return cur
    },
    filterNode(val, data) {
      if (!val) return true
      return data.level !== val
    },
    checkChange(data, checked, indeterminate) {
      if (checked) {
        this.$refs.mytree.setCheckedKeys([data.id])
        this.form.pName = data.name
        this.form.parentId = data.id
      } else if (data.name == this.form.pName) {
        this.form.pName = ''
        this.form.parentId = ''
      }
    },
    handleIconItem(icon) {
      this.form.icon = icon
    },
    /* 添加、编辑 */
    saves(formName) {
      this.$refs[formName].validate(async (valid) => {
        if (valid) {
          const obj = this.$options.data().form
          switch (this.form.level) {
            case 0:
              obj.id = this.form.id
              obj.level = 0
              obj.name = this.form.name
              obj.path = this.form.path
              obj.icon = this.form.icon
              obj.sortNumber = this.form.sortNumber
              break
            case 1:
              obj.id = this.form.id
              obj.level = 1 //权限等级
              obj.name = this.form.name //权限名称
              obj.parentId = this.form.parentId //parentId  上级ID
              obj.pName = this.form.pName
              obj.path = this.form.path //路由
              obj.icon = this.form.icon
              obj.sortNumber = this.form.sortNumber //sortNumber  排序
              break
            case 2:
              obj.id = this.form.id
              obj.level = 2
              obj.name = this.form.name
              obj.pName = this.form.pName
              obj.parentId = this.form.parentId
              obj.permission = this.form.permission
              obj.sortNumber = this.form.sortNumber
              break
          }
          this.btn_loading = true
          let res = ''
          if (obj.id) {
            res = await editMenu(obj)
          } else {
            res = await addMenu(obj)
          }
          this.btn_loading = false
          if (res.code !== 200) return false
          Object.assign(this.$data, this.$options.data())
          this.$layer.close(this.layerid)
          this.$parent.getList()
          this.$message({ message: '操作成功', type: 'success' })
        } else {
          this.$refs[formName].validate()
        }
      })
    },
    close() {
      this.$layer.close(this.layerid)
    },
  },
}
</script>

<style lang="scss" scoped></style>
